package a4;

import java.util.ArrayList;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class PposEval {
	ArrayList<String> pos;
	ArrayList<String> ppos;
	SortedMap<String, SortedMap<String, Integer> > pposCounts;
	SortedMap<String, Integer> posCounts;
	double[][] confMat;
	boolean built = false;
	
	public PposEval(ArrayList<String> pos, ArrayList<String> ppos){
		pposCounts = new TreeMap<String,SortedMap<String, Integer> >();
		posCounts = new TreeMap<String, Integer>();
		this.pos = pos;
		this.ppos = ppos;
		initialize();
	}
	
	private void initialize(){
		for(int i = 0; i < pos.size(); i++){
			if(pposCounts.containsKey(pos.get(i))){
				SortedMap<String, Integer> tagCount = pposCounts.get(pos.get(i));
				int count = tagCount.containsKey(ppos.get(i)) ? tagCount.get(ppos.get(i)) : 0;
				tagCount.put(ppos.get(i), count + 1);
				pposCounts.put(pos.get(i), tagCount);
			}else{
				SortedMap<String, Integer> tagCount = new TreeMap<String, Integer>();
				tagCount.put(ppos.get(i), 1);
				pposCounts.put(pos.get(i), tagCount);
			}
			
			int c = posCounts.containsKey(pos.get(i)) ? posCounts.get(pos.get(i)) : 0;
			posCounts.put(pos.get(i), c + 1);
		}
	}
	
	public double accuracy(){
		double correctPpos = 0;
		double wrongPpos = 0;
		for(int i = 0; i < pos.size(); i++){
			if(pos.get(i).equals(ppos.get(i))){
				correctPpos++;
			}else{
				wrongPpos++;
			}			
		}		
		return correctPpos/(correctPpos + wrongPpos);
	}
	
	private void buildConfusionMatrix(){
		Set<String> tags = pposCounts.keySet();
		double[][] confMat = new double[tags.size()][tags.size()];
		int i = 0;
		for(String t : tags){
			SortedMap<String, Integer> ptagCounts = pposCounts.get(t);
			int j = 0;
			for(String pt : tags){
				if(ptagCounts.containsKey(pt)){
					confMat[i][j] = (double)ptagCounts.get(pt)/(double)posCounts.get(t);
				}
				j++;
			}
			i++;
		}
		this.confMat = confMat;
		built = true;
	}
	
	public void printConfMat(){
		if(!built) buildConfusionMatrix();
		Set<String> tagSet = pposCounts.keySet();
		Object[] tags = tagSet.toArray();
		for(int i = 0; i < tags.length; i++){
			System.out.print("\t" + tags[i]);
		}
		for(int i = 0; i < tags.length; i++){
			System.out.print("\n" + tags[i]);
			for(int j = 0; j < tags.length; j++){
				System.out.print("\t" + confMat[i][j]);
			}
		}
		System.out.flush();
	}
}
